package org.goatsoft.catchpeaks;

import java.awt.List;
import java.util.Set;

import org.goatsoft.catchpeaks.Util;

public class DPlayer implements Player {

	private static int[] cardsWithNoRight = { 4, 6, 8, 11, 14, 17, 27 };
	private static int[] cardsWithNoLeft = { 3, 5, 7, 9, 12, 15, 18 };
	private static int[] lastCards = { 0, 1, 2 };

	@Override
	public void gameStarted() {
	}

	@Override
	public int move(Card[] state) {

		int maxScore = 0;
		int maxCardsRevealed = 0;
		int bestOption = state.length - 1;

		for (int option = state.length - 2; option >= 0; option--) {
			if (Util.isValidMove(state, option)) {
				int cardsRevealed = getNumOfRevealedCards(state, option);

				Card[] copyOfState = createCopy(state);
				copyOfState[copyOfState.length - 1] = copyOfState[option];
				copyOfState[option] = null;

				int optionScore = 1 + getOptionScore(copyOfState);
				if (optionScore > maxScore) {
					maxScore = optionScore;
					bestOption = option;
				}else if(optionScore==maxScore && cardsRevealed>maxCardsRevealed){
					bestOption = option;
				}
			}
		}
		return bestOption;
	}

	private int getNumOfRevealedCards(Card[] state, int i) {
		if (i == 0 || i == 1 || i == 2) {
			return 0;
		} else if (isInList(cardsWithNoRight, i)) {
			if (state[i - 1] == null) {
				return 1;
			}else{
				return 0;
			}
		} else if (isInList(cardsWithNoLeft, i)) {
			if (state[i + 1] == null) {
				return 1;
			}else{
				return 0;
			}
		}
		
		if((state[i-1] == null && state[i+1] !=null)||(state[i-1] != null && state[i+1] == null)){
			return 1;
		}else if(state[i-1] == null && state[i+1] ==null){
			return 2;
		}else{
			return 0;
		}
	}

	private boolean isInList(int[] list, int i) {
		for (int j = 0; j < list.length; j++) {
			if (list[j] == i) {
				return true;
			}
		}
		return false;
	}

	private Card[] createCopy(Card[] state) {
		Card[] copy = state.clone();
		for (int i = state.length - 2; i >= 0; i--) {
			if (Util.isFaceDown(state, i)) {
				copy[i] = null;
			}
		}
		return copy;
	}

	private int getOptionScore(Card[] state) {
		int maxScore = 0;
		for (int option = state.length - 2; option >= 0; option--) {

			if (Util.isValidMove(state, option)) {
				Card[] copyOfState = state.clone();
				copyOfState[copyOfState.length - 1] = copyOfState[option];
				copyOfState[option] = null;
				int optionScore = 1 + getOptionScore(copyOfState);
				if (optionScore > maxScore) {
					maxScore = optionScore;
				}
			}
		}
		return maxScore;
	}

	@Override
	public void gameEnded() {

	}

}
